package com.hodge.core.utils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * Created by 张皓竣 on 2020/9/20
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SpringContextUtil implements ApplicationListener<ContextRefreshedEvent> {
    private final ApplicationContext applicationContext;
    private static ApplicationContext CONTEXT;

    //获取上下文
    public static ApplicationContext getApplicationContext() {
        return CONTEXT;
    }

    //通过类型获取上下文中的 bean
    public static <T> T getBean(Class<T> requiredType){
        return CONTEXT.getBean(requiredType);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        CONTEXT = applicationContext;
        log.info(" ======= App加载完成 ======= ");
    }
}
